#coding:utf-8
import datetime
import simplejson
# 几乎所有的函数都可以包装成为 jsonrpc, 只要他的参数及返回值能够 json 化, 能 json 化的对象包括 
# None, True, False, 整数, 浮点数, 字符串, tuple(会被转化为list), list, dict(字典的key会被转化为字符串), 
# 以及这些对象的嵌套形式.

class _Encoder(simplejson.JSONEncoder):
    def default(self, a):
        if isinstance(a, datetime.datetime):
            return {'__datetime__': (a.year, a.month, a.day, a.hour, a.minute, a.second, a.microsecond)}
        elif isinstance(a, datetime.date):
            return {'__date__': (a.year, a.month, a.day)}
        elif isinstance(a, set):
            return {'__set__': list(a)}
        return super(_Encoder, self).default(a)

def jsonserial(obj):
    return simplejson.dumps(obj, cls=_Encoder)
dumps = jsonserial


class _Decoder:
    def __call__(self, dct):
        if '__datetime__' in dct:
            return datetime.datetime(*dct['__datetime__'])
        elif '__date__' in dct:
            return datetime.date(*dct['__date__'])
        elif '__set__' in dct:
            return set(dct['__set__'])
        return dct

def jsondeserial(obj):
    return simplejson.loads(obj,object_hook=_Decoder())
loads = jsondeserial
